package com.changanw.storage.service;

import com.changanw.storage.mapper.StorageMapper;
import com.changanw.storage.model.Storage;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 */
@Service
public class StorageService {
    private static Logger logger =  LoggerFactory.getLogger(StorageService.class);
    @Autowired
    StorageMapper storageMapper;

    public boolean prepare(BusinessActionContext context, String productId, Integer count) {
        Storage storage = storageMapper.getStorageByProductId(productId);
        if (storage == null){
            throw new RuntimeException("商品不存在");
        }
        if (storage.getCount() < count){
            throw new RuntimeException("库存不足");

        }
        storage.setCount(storage.getCount()-count);
        storage.setFreezeCount(storage.getFreezeCount()+count);
        Integer i = storageMapper.updateStorage(storage);
        logger.info("{} 商品冻结 {} 个",productId,count);
        return i==1;
    }

    public boolean commit(BusinessActionContext context) {
        String productId = (String) context.getActionContext("productId");
        Integer count = (Integer) context.getActionContext("count");
        Storage storage = storageMapper.getStorageByProductId(productId);
        if (storage.getFreezeCount() < count){
            throw new RuntimeException("库存不足");
        }
        storage.setFreezeCount(storage.getFreezeCount()-count);
        Integer i = storageMapper.updateStorage(storage);
        logger.info("{} 商品扣除 {} 个",productId,count);
        return i==1;
    }

    public boolean rollback(BusinessActionContext context) {
        String productId = (String) context.getActionContext("productId");
        Integer count = (Integer) context.getActionContext("count");
        Storage storage = storageMapper.getStorageByProductId(productId);
        if (storage.getFreezeCount() >=count){
            storage.setCount(storage.getFreezeCount() - count);
            storage.setFreezeCount(storage.getCount() + count);
            Integer integer = storageMapper.updateStorage(storage);
            logger.info("{} 商品释放库存 {} 个",productId,count);
            return integer == 1;
        }
        logger.info("{} 商品释放{} 个",productId,count);
        return true;
    }
}
